<?php 
class ControllerSurveyQuestion extends Controller {
	private $error = array();
	
	public function index() {  
    	$this->language->load('survey/question');
		$this->load->model('survey/question');
		
		$question_id = $this->request->get['question_id'];
		$question_info = $this->model_survey_question->getQuestion($question_id);
		
		if (isset($this->request->get['filter_survey_id'])) {
			$filter_survey_id = $this->request->get['filter_survey_id'];
		} else if(isset($this->session->data['survey_id'])) {
			$filter_survey_id = $this->session->data['survey_id'];
		} else {
			$filter_survey_id = $question_info['survey_id'];		
		}
		
		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'p.sort_order';
		} 

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}
  		
		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}
				
		if (isset($this->request->get['limit'])) {
			$limit = $this->request->get['limit'];
		} else {
			$limit = $this->config->get('config_catalog_limit');
		}
		
		$this->data['breadcrumbs'] = array();
		
      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home'),
        	'separator' => false
      	);
      	
      	$data = array(
			'filter_survey_id'  => $filter_survey_id, 
			'sort'                => $sort,
			'order'               => $order,
//			'start'               => ($page - 1) * $limit,
//			'limit'               => $limit
		);
		
		$survey_info = $this->model_survey_question->getQuestions($data);
		$all_question_keys = array_keys($survey_info);
		
		if (count($question_info) > 0) {
			
			$this->load->model('localisation/language');			
			$language_id = $this->model_localisation_language->getLanguageByCode($this->session->data['language']);
			$language_id = $language_id['language_id'];
			$customer_id = $this->customer->getId();
			if(isset($this->session->data['guest_id']))
				$guest_id = $this->session->data['guest_id'];
			else
				$guest_id = 0;
				
			$data = array(
				'email' => $this->session->data['email'],
				'survey_id' => $question_info['survey_id'],
				'guest_id' => $guest_id,
				'customer_id' => $customer_id,
				'question_id' => $question_id,
				'language_id' => $language_id,
			);					
			
			$check_answer = $this->model_survey_question->checkAnswer($data);
			
			if($this->request->server['REQUEST_METHOD'] == "POST") {
				
				if($this->validateForm($question_info)) {
					
					$time_took = strtotime(date('Y-m-d H:i:s')) - strtotime($this->session->data['start_time']);
					
					if(isset($this->request->post['answer_'.$question_id])) {
						$answer = $this->request->post['answer_'.$question_id];
						if(is_array($answer)) {
									
							if(count($check_answer) > 0) {											
									$this->model_survey_question->deleteAnswers($data);
							}
							
							foreach($answer as $each_option) {
								$data = array (
									'email' => $this->session->data['email'],
									'survey_id' => $question_info['survey_id'],
									'guest_id' => $guest_id,
									'customer_id' => $customer_id,
									'question_id' => $question_id,
									'language_id' => $language_id,
									'answer' => $each_option,
									'ip' => $this->request->server['REMOTE_ADDR'],
									'time_took' => $time_took,
									'date_added' => date("Y-m-d H:i:s"),
									'date_modified' => date("Y-m-d H:i:s")
								);

								$this->model_survey_question->addAnswer($data);
							}
						} else {
							$data = array(
								'email' => $this->session->data['email'],
								'survey_id' => $question_info['survey_id'],
								'guest_id' => $guest_id,
								'customer_id' => $customer_id,
								'question_id' => $question_id,
								'language_id' => $language_id,
								'answer' => $answer,
								'ip' => $this->request->server['REMOTE_ADDR'],
								'time_took' => $time_took,
								'date_added' => date("Y-m-d H:i:s"),
								'date_modified' => date("Y-m-d H:i:s")
							);
							
							if(count($check_answer) > 0) {
								$data['answer_id'] = $check_answer['answer_id'];
								$this->model_survey_question->editAnswer($data);
							} else {
								$this->model_survey_question->addAnswer($data);						
							}	
						}
					}
					
					$next_question = $this->getNext($all_question_keys, $question_id);
					
					if($next_question)
						$this->redirect($next_question);
					else
						$this->redirect($this->url->link('survey/survey/finished', 'survey_id=' .  $question_info['survey_id']));
				}
			}
	  		
	  		$this->document->setTitle($question_info['title']);
	  		
	  		$this->load->model('survey/survey');
	  		$surveyInfo = $this->model_survey_survey->getSurvey($question_info['survey_id']);
	  		
	  		$this->data['breadcrumbs'][] = array(
        		'text'      => $question_info['title'],
				'href'      => $this->url->link('survey/survey', 'survey_id=' .  $question_info['survey_id']),      		
        		'separator' => $this->language->get('text_separator')
      		); 

      		
      		/*$this->data['breadcrumbs'][] = array(
        		'text'      => $question_info['title'],
				'href'      => $this->url->link('survey/question', 'question_id=' .  $question_id),      		
        		'separator' => $this->language->get('text_separator')
      		);*/		
						
//      		$this->data['heading_title'] = $question_info['sort_order'] . ". " . $question_info['title'];
      		
      		$question_num = "";
			if(!empty($question_info['qnum']))
				$question_num = $question_info['qnum']." ";
						
      		$this->data['heading_title'] = $question_num.nl2br($question_info['title']);
      		
      		if(isset($this->error['warning'])) {
      			$this->data['error_warning'] = $this->error['warning']; 	
      		} else {
      			$this->data['error_warning'] = "";
      		}
      		
      		if(isset($this->error['question'])) {
      			$this->data['error_question'] = $this->error['question']; 	
      		} else {
      			$this->data['error_question'] = "";
      		}
      		
      		$options = array();
      		$this->data['question_id'] = $question_id;
      		
      		switch ($question_info['qtype']) {
      			case 'radio' :
		      		$question_info['lable'] = str_replace("\r","", $question_info['lable']);
		      		$all_lables = explode("\n", $question_info['lable']);
		      		if(!empty($question_info['value'])) {
		      			$question_info['value'] = str_replace("\r","", $question_info['value']);
		      			$all_values = explode("\n", $question_info['value']);
		      		} else {
		      			$all_values = $all_lables;
		      		}      			
		      		
		      		if(!empty($check_answer['answer']))
		      			$default_value = $check_answer['answer'];
		      		else
		      			$default_value = $question_info['default'];
		      		
		      		foreach($all_lables as $key => $each_value) {
		      			      			
		      			$default = 0;
		      			if($default_value == $all_values[$key])
		      				$default = 1;
		      				
		      		    $options[] = array(
			      			'lable' => $all_lables[$key],
			      			'value' => $all_values[$key],
			      			'default' => $default
			      		);	
		      		}      			
      			break;
      			case 'checkbox' :
      				$check_answer = $this->model_survey_question->checkAnswers($data);
      				
		      		$question_info['lable'] = str_replace("\r","", $question_info['lable']);
		      		$all_lables = explode("\n", $question_info['lable']);
		      		if(!empty($question_info['value'])) {
		      			$question_info['value'] = str_replace("\r","", $question_info['value']);
		      			$all_values = explode("\n", $question_info['value']);
		      		} else {
		      			$all_values = $all_lables;
		      		}      			
		      		
		      		if(count($check_answer) > 0) {		      			
		      			foreach($check_answer as $each_option) {
							$default_value[] = $each_option['answer'];
						}
		      		} else {
		      			$default_value = explode("\n", $question_info['default']);
		      		}
		      			
		      		
		      		foreach($all_lables as $key => $each_value) {
		      			      			
		      			$default = 0;
		      			if(in_array($all_values[$key], $default_value))
		      				$default = 1;
		      				
		      		    $options[] = array(
			      			'lable' => $all_lables[$key],
			      			'value' => $all_values[$key],
			      			'default' => $default
			      		);	
		      		}      			
      			break;
      			case 'textarea' :
					$options = array(
		      			'lable' => $question_info['lable'],
		      			'value' => $question_info['value'],
		      			'default' => $question_info['default']
		      		);      					
      			break;
      		}      		
//      		print_r($question_info);
//      		print_r($options);
      		
      		$this->data['options'] = $options;
      		
      		$this->data['qtype'] = $question_info['qtype'];

      		
      		$this->data['button_prev'] = $this->language->get('button_prev');
      		$this->data['button_next'] = $this->language->get('button_next');
			
			$this->data['description'] = html_entity_decode($question_info['description'], ENT_QUOTES, 'UTF-8');
      		
      		$this->data['action'] = $this->url->link('survey/question', 'question_id=' . $question_id);
      		
      		$get_previous = $this->getPrev($all_question_keys, $question_id);
      		if(empty($get_previous))
      			$get_previous = $this->url->link('survey/survey', 'survey_id=' . $question_info['survey_id']);
      			
			$this->data['prev'] = $get_previous;
			$this->data['next'] = "javascript:$('#form').submit();";

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/survey/question.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/survey/question.tpl';
			} else {
				$this->template = 'default/template/survey/question.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
						
	  		$this->response->setOutput($this->render());
    	} else {
      		$this->data['breadcrumbs'][] = array(
        		'text'      => $this->language->get('text_error'),
				'href'      => $this->url->link('survey/question', 'question_id=' . $question_id),
        		'separator' => $this->language->get('text_separator')
      		);
				
	  		$this->document->setTitle($this->language->get('text_error'));
			
      		$this->data['heading_title'] = $this->language->get('text_error');

      		$this->data['text_error'] = $this->language->get('text_error');

      		$this->data['button_continue'] = $this->language->get('button_continue');

      		$this->data['continue'] = $this->url->link('common/home');

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
			} else {
				$this->template = 'default/template/error/not_found.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
					
	  		$this->response->setOutput($this->render());
    	}
  	}
  	
  	public function getPrev($all_questions, $question_id) {
  		$question_id = array_search($question_id, $all_questions);
  		$question_id--;
  		if(isset($all_questions[$question_id]))
  			return $this->url->link('survey/question', 'question_id=' . $all_questions[$question_id]);
  		else
  			return 0;
  	}
  	
  	public function getNext($all_questions, $question_id) {
  		$question_id = array_search($question_id, $all_questions);
  		$question_id++;
  		if(isset($all_questions[$question_id]))
  			return $this->url->link('survey/question', 'question_id=' . $all_questions[$question_id]);
  		else
  			return 0;
  	}
  	
  	public function start() {
  		$this->session->data['question_id'] = $this->request->get['question_id'];
  		$this->redirect($this->url->link('survey/question'));
  		exit;
  	}
  	
  	public function validateForm($question_info = array()) {
  		
  		$question_id = $this->request->get['question_id'];
  		
  		if($question_info['required']) {
  			if(empty($this->request->post['answer_'.$question_id]))	
  				$this->error['question'] = $this->language->get('error_question');
  		}
  		
  		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}
  		
  		if (!$this->error) {
			return true;
		} else {
			return false;
		}
  	}
	
	public function info() {
		$this->load->model('survey/question');
		
		if (isset($this->request->get['question_id'])) {
			$question_id = $this->request->get['question_id'];
		} else {
			$question_id = 0;
		}      
		
		$question_info = $this->model_survey_question->getQuestion($question_id);

		if ($question_info) {
			$output  = '<html dir="ltr" lang="en">' . "\n";
			$output .= '<head>' . "\n";
			$output .= '  <title>' . $question_info['title'] . '</title>' . "\n";
			$output .= '  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . "\n";
			$output .= '</head>' . "\n";
			$output .= '<body>' . "\n";
			$output .= '  <br /><br /><h1>' . $question_info['title'] . '</h1>' . "\n";
			$output .= html_entity_decode($question_info['description'], ENT_QUOTES, 'UTF-8') . "\n";
			$output .= '  </body>' . "\n";
			$output .= '</html>' . "\n";			

			$this->response->setOutput($output);
		}
	}
}
?>